package desktop.core.bar;

import pulpcore.Input;
import pulpcore.animation.Timeline;
import desktop.conf.key.KeyConf;
import desktop.core.playfield.PlayFieldViewAbstract;

public class BarController {
	protected static final int UN_PRESSED = -1;
	protected int keyPressed;
	protected KeyConf keyConf;

	Timeline timeline = null;

	public BarController(KeyConf keyConf) {
		this.keyConf = keyConf;
	}

	public void controlBar(PlayFieldViewAbstract playFieldView, Bar bar,
			boolean left, boolean right, double yBottom, int elapsedTime) {
		searchKeyPressed();
		timeline = drop(bar, elapsedTime);
		playFieldView.addTimeline(timeline);
		timeline = shift(bar);
		playFieldView.addTimeline(timeline);
		timeline = moveLeft(bar, left, elapsedTime);
		playFieldView.addTimeline(timeline);
		timeline = moveRight(bar, right, elapsedTime);
		playFieldView.addTimeline(timeline);
		timeline = moveDown(bar, yBottom, elapsedTime);
		playFieldView.addTimeline(timeline);
	}

	private void searchKeyPressed() {
		this.keyPressed = UN_PRESSED;
		this.testKeyPressed(this.keyConf.getDown());
		this.testKeyPressed(this.keyConf.getLeft());
		this.testKeyPressed(this.keyConf.getRight());
		this.testKeyPressed(this.keyConf.getShift());
	}

	private void testKeyPressed(int keyPressed) {
		if (Input.isPressed(keyPressed)) {
			this.keyPressed = keyPressed;
		}
	}

	private Timeline drop(Bar bar, int elapsedTime) {
		timeline = bar.dropByGravity(elapsedTime);
		return timeline;
	}

	private Timeline shift(Bar bar) {
		if (this.keyPressed == this.keyConf.getShift()) {
			timeline = bar.shift();
			return timeline;
		} else {
			return null;
		}

	}

	private Timeline moveLeft(Bar bar, boolean canMoveLeft, int elapsedTime) {
		if ((this.keyPressed == this.keyConf.getLeft()) && (canMoveLeft)) {
			timeline = bar.moveLeft(elapsedTime);
			return timeline;
		} else {
			return null;
		}
	}

	private Timeline moveRight(Bar bar, boolean canMoveRight, int elapsedTime) {
		if ((this.keyPressed == this.keyConf.getRight()) && (canMoveRight)) {
			timeline = bar.moveRight(elapsedTime);
			return timeline;
		} else {
			return null;
		}
	}

	private Timeline moveDown(Bar bar, double yBottom, int elapsedTime) {
		if (this.keyPressed == this.keyConf.getDown()) {
			timeline = bar.moveDownDirectly(yBottom, elapsedTime);
			return timeline;
		} else {
			return null;
		}
	}

}